package com.hongtech.tiny.modules.app.controller;

import com.hongtech.tiny.common.response.ObjectResult;
import com.hongtech.tiny.modules.app.form.RegisterForm;
import com.hongtech.tiny.modules.knowledge.entity.UserEntity;
import com.hongtech.tiny.modules.knowledge.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 注册
 */
@RestController
@RequestMapping("/app")
@Api(tags = "注册接口")
public class RegisterController {

    @Resource
    private UserService userService;

    @PostMapping("register")
    @ApiOperation("用户注册")
    public ObjectResult<String> register(@RequestBody @Validated RegisterForm form) {
        if (!StringUtils.isNotEmpty(form.getMobile())) {
            return ObjectResult.validateFailed();
        }
        if (!StringUtils.isNotEmpty(form.getPassword())) {
            return ObjectResult.validateFailed();
        }
        UserEntity exitUser = userService.getUserInfoByMobile(form.getMobile());
        if (exitUser != null) {
            return ObjectResult.failed("账号已存在！");
        }
        UserEntity user = new UserEntity();
        user.setMobile(form.getMobile());
        user.setUsername(form.getMobile());
        user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        if (userService.save(user)) {
            return ObjectResult.success("注册成功！");
        }
        return ObjectResult.failed("注册失败！");
    }

}
